<template>
  <div>
    <div class="head-container">
      <el-input
        v-model="filterText"
        placeholder="请输入名称"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
    </div>
    <div class="head-container" :style="{height: `calc(100vh - ${heightDiff})`, overflowX: 'scroll'}">
      <el-tree
        :data="data"
        :props="defaultProps"
        :filter-node-method="filterNode"
        ref="tree"
        node-key="catId"
        :expand-on-click-node="false"
        highlight-current
        @node-click="handleNodeClick"

        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'CategoryTree',
  data() {
    return {
      filterText: '',
      data: [],
      loading: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getTree()
  },
  methods: {
    getTree() {
      this.loading = true
      this.$api.get('/product/category/tree').then(({ data }) => {
        this.data = data.data
        this.loading = false
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data, node, self) {
      this.$emit('tree-click', data, node)
    },
    setCurrentKey(value) {
      this.filterText = ''
      this.$refs.tree.setCurrentKey(value)
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  props: {
    /**
     * 最终高度=默认高度-heightDiff
     */
    heightDiff: {
      type: String,
      default: '0px'
    }
  }
}
</script>

<style scoped>

</style>
